package dynamicproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author gaopeng
 * @date 2019/12/8 8:45 下午
 */
public class DynamicProxy {

    private IAdvice advice;

    public DynamicProxy(IAdvice advice) {
        this.advice = advice;
    }

    public <T> T newProxyInstance(Class<T> tClass){
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object o = null;
                try {
                    advice.before();
                    //代理类
                    System.out.println(proxy.getClass());
                    T obj = tClass.newInstance();
                    o = method.invoke(obj,args);
                    advice.after();
                }catch (Exception e){
                    advice.exception();
                }finally {
                    advice.returning();
                }
                return o;
            }
        };
        return (T) Proxy.newProxyInstance(tClass.getClassLoader(), tClass.getInterfaces(), handler);
    }
}
